package com.my.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.my.domain.ParkingSpace;
import com.my.domain.Result;
import com.my.encryption.MyEncrypt;
import com.my.mapper.ParkingSpaceMapper;
import com.my.service.ParkingSpaceService;
import com.my.websocket.WebSocketClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@CrossOrigin//让这个控制器支持跨域请求
@Controller
@RequestMapping("/park")
public class SensorParkingController {//这个Controller只允许传感器访问，通过加密参数识别是传感器的请求
    @Autowired
    private ParkingSpaceService parkingSpaceService;

    private static final DateFormat df = new SimpleDateFormat("HH:mm:ss");

    @RequestMapping(path = "/s", method = RequestMethod.POST, params = {"id", "code"})
    @ResponseBody
    public Result parking(Integer id, String code) {//停车（模拟用，实际的停车由传感器触发）
        //对加密参数code解密，得到 id和时间 //HH:mm:ss#id
        String[] strs = MyEncrypt.decode(code).split("#");
        if (strs.length != 2) {
            return Result.newErrResult("加密参数不合法");
        }
        if (!id.toString().equals(strs[1])) {
            return Result.newErrResult("加密参数不合法（id）");
        }
        Date time;
        try {
            time = df.parse(strs[0]);
        } catch (ParseException e) {
            return Result.newErrResult("加密参数不合法（time）");
        }
        Date now = new Date();
        if (Math.abs(now.getTime() - time.getTime()) < 60 * 1000) { //判断 time 和 now 是否在一分钟内
            ParkingSpace parkingSpace = parkingSpaceService.findById(id);
            if (parkingSpace == null) {
                return Result.newErrResult("没有这个车位");
            }
            if (parkingSpace.getLocked()) {
                return Result.newErrResult(id + "号车位已被预约或占用，不能停入");
            }
            Result result = parkingSpaceService.parking(id);
            result.setMsg("停车成功，开始计费");
            return result;
        } else {
            return Result.newErrResult("加密参数不合法（time）");
        }
    }
}
